package com.stock.core.task;

import com.stock.api.service.stock.StockCodeService;
import com.stock.api.service.stock.StockHistoryService;
import com.stock.comm.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <p>更新股票历史数据任务</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @createTime: 2016/9/13 17:49
 */
@Service("stockHistoryTask")
public class StockHistoryTask extends BaseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(StockHistoryTask.class);

    @Resource
    private StockCodeService stockCodeService;

    @Resource
    private StockHistoryService stockHistoryService;

    /**
     * 创建线程池
     */
    ExecutorService pool = null;

    /**
     * 定时任务处理
     */
    public void run() throws Exception {
        LOGGER.info("更新股票历史数据任务开始···");
        String startDate = DateUtil.getCurrentDatetime();
        boolean flag = true;
        Date date = DateUtil.stringToDate("20160731", DateUtil.DATESHORTFORMAT);
        final String stockCode = "600415";
        pool = Executors.newFixedThreadPool(10);
        List<Future> rowResult = new CopyOnWriteArrayList<>();
        while (flag) {
            //日期加1
            date = DateUtil.addDate(date, 1);
            final String finalDate = DateUtil.date2String(date, DateUtil.DATESHORTFORMAT);
            rowResult.add(pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        //更新历史数据
                        stockHistoryService.extactStockHistoryData(finalDate, stockCode);
                    } catch (Exception e) {
                        LOGGER.error("抓取股票：" + stockCode + "成交数据失败！", e);
                    }
                }
            }));
            //当前日期停止
            if (DateUtil.formatCurrentDate().replaceAll("-", "").equals(DateUtil.date2String(date, DateUtil.DATESHORTFORMAT)))
                flag = false;
        }
        //等待处理结果
        for (Future f : rowResult) {
            f.get();
        }
        //启动一次顺序关闭，执行以前提交的任务，但不接受新任务。如果已经关闭，则调用没有其他作用
        pool.shutdown();
        String endDate = DateUtil.getCurrentDatetime();
        LOGGER.info("更新股票历史数据任务耗时：" + DateUtil.dateDiff(startDate, endDate));
    }
}
